package businessLogic;

import businessEntities.NodeData;
import businessEntities.QueryResultContainer;
import businessEntities.exceptions.ConnectionException;
import businessEntities.exceptions.QueryException;
import dataAccess.DALQueryExecutor;

/**
 * Logic layer between the user that asks data from the database 
 * to the data access layer that execute queries on the database
 */
public class BLQueryMenager {

    /**
     * Returns QueryResultContainer object witch holds the whole requested database table.
     * @return QueryResultContainer with the data of the whole table or <code>null</code> for any exception. 
     */
    public QueryResultContainer getWholeTable(String dbName, String table) {
        DALQueryExecutor queryExecutor = new DALQueryExecutor();
        QueryResultContainer result = null;

        try {
            result = queryExecutor.getWholeTable(dbName, table);
        } catch (QueryException | ConnectionException ex) {
            return null;
        }

        return result;
    }

    /**
     * Returns QueryResultContainer object witch holds result according to nodeData
     * @return QueryResultContainer with the data of the filtered table or <code>null</code> for any exception.
     */
    public QueryResultContainer getFilteredTable(NodeData nodeData) {
        if (nodeData.isRootFilter()) {
            return getWholeTable(nodeData.getDataBaseName(), nodeData.getTableName());
        } else {
            String dataBaseName = nodeData.getDataBaseName();
            String tableName = nodeData.getTableName();
            String where = nodeData.getWhereSentence();
            DALQueryExecutor queryExecutor = new DALQueryExecutor();
            QueryResultContainer result = null;

            try {
                result = queryExecutor.getTableWhere(dataBaseName, tableName, where);
            } catch (QueryException | ConnectionException ex) {
                return null;
            }

            return result;
        }
    }
}
